// package main

// import "github.com/gin-gonic/gin"

// func main() {
// 	r := gin.Default()
// 	r.GET("/ping", func(c *gin.Context) {
// 		c.JSON(200, gin.H{
// 			"message": "pa!",
// 		})
// 	})
// 	r.Run() // 监听并在 0.0.0.0:8080 上启动服务
// }

package main

import (
	// "fmt"
	"log"
	"net/http"
	"os"
	// "time"

	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var identityKey = "id"
var db *gorm.DB
var r *gin.Engine

func initDB() {
	// sqlite
	var err error
	db, err = gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	db.AutoMigrate(&User{}, &Todo{})
}

func main() {
	initDB()

	port := os.Getenv("PORT")
	r = gin.New()
	r.Use(gin.Logger())
	r.Use(gin.Recovery())
	r.LoadHTMLGlob("templates/*")

	if port == "" {
		port = "8000"
	}

	// the jwt middleware
	authMiddleware := initAuthMiddleware()

	r.GET("/", HomeHandler)
	r.GET("/account", AccountHandler)
	r.POST("/login", authMiddleware.LoginHandler)

	r.NoRoute(authMiddleware.MiddlewareFunc(), func(c *gin.Context) {
		claims := jwt.ExtractClaims(c)
		log.Printf("NoRoute claims: %#v\n", claims)
		c.JSON(404, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"})
	})

	auth := r.Group("/auth")
	// Refresh time can be longer than token timeout
	auth.GET("/refresh_token", authMiddleware.RefreshHandler)
	auth.Use(authMiddleware.MiddlewareFunc())
	{
		auth.GET("/hello", helloHandler)
	}

	todo := r.Group("/todo")
	todo.Use(authMiddleware.MiddlewareFunc())
	{
		todo.GET("/new", NewTodoHandler)
		todo.POST("/create", CreateTodoHandler)
		todo.GET("/list", TodoListHandler)
		todo.POST("/finish", FinishTodoHandler)
	}

	approve := r.Group("/approve")
	approve.Use(authMiddleware.MiddlewareFunc())
	{
		approve.GET("/list", ApproveListHandler)
		approve.POST("/todo", ApproveHandler)
	}

	if err := http.ListenAndServe("localhost:"+port, r); err != nil {
		log.Fatal(err)
	}
}
